package com.easy.easybook.controller;

import com.aliyun.oss.OSS;
import com.easy.easybook.dao.BookMapper;
import com.easy.easybook.entity.Books;
import com.easy.easybook.entity.Category;
import com.easy.easybook.entity.vo.BooksVo;
import com.easy.easybook.service.BookService;
import com.easy.easybook.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.print.Book;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;


/**
 * @author http://zouyujie.top
 * @date 2021/12/19 14:36
 */
@RestController
@RequestMapping("/books")
public class BooksController {
    private final String BucketName = "easy-book";
    private final String endpoint = "??";
    @Autowired
    OSS ossClient;
    @Autowired
    BookService bookService;
    @Autowired
    BookMapper bookMapper;
    @ResponseBody
    @GetMapping("/list")
    public R list(){
        return R.ok().put("data", bookService.selectAll());
    }
    @ResponseBody
    @PostMapping("/update")
    public R update(@RequestBody BooksVo booksVo){
        bookMapper.update(booksVo.getName(), booksVo.getUrl(), booksVo.getStock(), booksVo.getCid(), booksVo.getId());
        return R.ok();
    }
    @ResponseBody
    @PostMapping("/add")
    public R add(@RequestBody BooksVo bookVo){
        Category category = new Category();
        category.setId(bookVo.getCid());
        Books books = new Books();
        books.setName(bookVo.getName());
        books.setUrl(bookVo.getUrl());
        books.setCategory(category);
        books.setStock(bookVo.getStock());
        int save = bookService.save(books);
        return R.ok();
    }
    @ResponseBody
    @PostMapping("/upload")
    public R upload(MultipartFile imageFile){
        InputStream inputStream = null;
        String url = null;
        try {
            inputStream =  imageFile.getInputStream();
            String fileName = imageFile.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String resultName = UUID.randomUUID()+suffix;
            url = "https://"+BucketName+"."+endpoint+"/"+resultName;
            ossClient.putObject(BucketName, resultName, inputStream);
        } catch (Exception e) {
            return R.ok().put("msg", imageFile.getOriginalFilename()+"上传失败");
        }
        return R.ok().put("url", url);
    }
    @ResponseBody
    @PostMapping("/delete")
    public R upload(@RequestBody Books books){
        bookMapper.delete(books.getId());
        return R.ok();
    }
    @ResponseBody
    @PostMapping("/search")
    public R search(@RequestBody Books books){
        if("".equals(books.getName())){
            return R.ok().put("data", bookMapper.listAll());
        }
        List<Books> booksList = bookMapper.selectBook(books.getName());
        return R.ok().put("data", booksList);
    }
}
